import {
  CloseCircleTwoTone,
  MinusCircleOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import {
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  FormItem,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  RadioGroup,
  RangePicker,
  Row,
  Space,
  Spin,
  Textarea,
  TypographyText
} from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { questionApi } from '@/apis'
import { ActData, QuesionItem } from '@/apis/questionTypes'
import UploadFile from '@/components/UploadFile'
import { useBack } from '@/hooks'
import { isValueEmpty } from '@/utils'

export default defineComponent({
  name: 'QAddOrEditAct',
  setup() {
    const { handleCancel } = useBack('refreshQuestionList')

    const loading = ref(false)
    const route = useRoute()
    const actData = ref({ isDisorder: true } as ActData)
    const showSortDialog = ref(false)
    const sortOld = ref(-1)
    const sortCur = ref(-1)
    const questionItemCur = ref({} as QuesionItem)
    const isPreview = ref(false)

    const questionListRef = ref()

    const saveLoading = ref(false)
    const publishLoading = ref(false)
    const containerRef = ref({} as any)

    onMounted(() => {
      init()
    })

    //初始化
    function init() {
      if (route.query.id) {
        isPreview.value = Boolean(route.query.preview)
        getDetail()
      } else {
        actData.value.questionList = []
        actData.value.timeRangeTemp = []
      }
    }

    //获取详情
    async function getDetail() {
      try {
        loading.value = true
        actData.value = await questionApi.getActivityDetail(route.query.id)
        actData.value.timeRangeTemp = actData.value.startTime
          ? [moment(actData.value.startTime), moment(actData.value.endTime)]
          : []
        actData.value.questionList.forEach(item => {
          item.perfected = true
        })
        loading.value = false
      } catch (e) {
        handleCancel()
      }
    }

    function checkFit(): boolean {
      if (!actData.value.activityTitle) {
        message.error('请输入活动标题')
        return false
      }
      if (actData.value.timeRangeTemp.length == 0) {
        message.error('请输入活动标题')
        return false
      }
      actData.value.startTime =
        actData.value.timeRangeTemp.length > 0
          ? actData.value.timeRangeTemp[0].format('x')
          : ''
      actData.value.endTime =
        actData.value.timeRangeTemp.length > 1
          ? actData.value.timeRangeTemp[1].format('x')
          : ''

      if (isValueEmpty(actData.value.questionPoint)) {
        message.error('请输入答对奖励')
        return false
      }
      if (!actData.value.backgroundImg) {
        message.error('请上传背景图')
        return false
      }
      if (!actData.value.activityRulesImg) {
        message.error('请上传规则图')
        return false
      }
      if (!actData.value.shareImg) {
        message.error('请上传分享图')
        return false
      }
      if (actData.value.questionList.length == 0) {
        message.error('至少添加一题')
        return false
      }
      if (!actData.value.questionList.every(item => item.perfected)) {
        message.error('请完善所有问题')
        return false
      }
      return true
    }

    //保存/发布
    async function saveOrPublish(isPublish: boolean) {
      if (!checkFit()) {
        return
      }

      try {
        actData.value.isRelease = isPublish
        if (isPublish) {
          publishLoading.value = true
        } else {
          saveLoading.value = true
        }
        if (actData.value.id) {
          await questionApi.editActivity(actData.value)
        } else {
          await questionApi.crateActivity(actData.value)
        }
        message.success('操作成功')
        handleCancel()
      } finally {
        if (isPublish) {
          publishLoading.value = false
        } else {
          saveLoading.value = false
        }
      }
    }

    //新增题目 0单选 1多选 2判断
    function addQuestion(questionType: 0 | 1 | 2) {
      let quesionItem: QuesionItem
      if (questionType == 2) {
        quesionItem = {
          questionType,
          perfected: false,
          optionList: [
            { optionDesc: '对', isCorrect: false, sort: 0 },
            { optionDesc: '错', isCorrect: false, sort: 1 }
          ],
          question: ''
        } as QuesionItem
      } else {
        quesionItem = {
          questionType,
          perfected: false,
          optionList: [{ optionDesc: '', isCorrect: false, sort: 0 }],
          question: ''
        } as QuesionItem
      }
      actData.value.questionList.push(quesionItem)
      editQuesion(actData.value.questionList.length - 1, quesionItem)

      nextTick(() => {
        questionListRef.value.scrollTo({
          top: questionListRef.value.scrollHeight,
          behavior: 'smooth'
        })
      })
    }
    //编辑题目
    function editQuesion(index, item: QuesionItem) {
      questionItemCur.value = JSON.parse(JSON.stringify(item))
      questionItemCur.value.sort = index
    }

    //排序
    function handleSort(index) {
      sortOld.value = index + 1
      sortCur.value = index + 1
      showSortDialog.value = true
    }

    function sortConfirm() {
      if (sortCur.value > actData.value.questionList.length) {
        sortCur.value = actData.value.questionList.length
      }
      if (sortOld.value != sortCur.value) {
        const temp = actData.value.questionList[sortOld.value - 1]
        actData.value.questionList.splice(sortOld.value - 1, 1)
        actData.value.questionList.splice(sortCur.value - 1, 0, temp)
        questionItemCur.value = {} as QuesionItem
      }
      showSortDialog.value = false
    }

    //编辑保存
    function handleEditSave() {
      if (!questionItemCur.value.question) {
        message.error('请输入问题')
        return
      }
      if (!questionItemCur.value.optionList.every(item => item.optionDesc)) {
        message.error('选项不能为空')
        return
      }
      if (!questionItemCur.value.optionList.some(item => item.isCorrect)) {
        message.error('至少添加一个正确选项')
        return
      }
      questionItemCur.value.optionList.forEach((item, index) => {
        item.sort = index
      })
      questionItemCur.value.perfected = true
      actData.value.questionList[questionItemCur.value.sort] = JSON.parse(
        JSON.stringify(questionItemCur.value)
      )
      message.success(`问题${questionItemCur.value.sort + 1}设置成功`)
    }

    return {
      loading,
      saveLoading,
      isPreview,
      publishLoading,
      actData,
      containerRef,
      questionItemCur,
      showSortDialog,
      sortCur,
      questionListRef,
      addQuestion,
      editQuesion,
      handleSort,
      sortConfirm,
      saveOrPublish,
      handleEditSave
    }
  },
  render() {
    return (
      <Spin spinning={this.loading}>
        <Row type="flex" justify="space-between">
          <h2>
            {() => {
              {
                let title = '新增活动'
                if (this.$route.query.id) {
                  if (this.isPreview) {
                    title = '查看活动'
                  } else {
                    title = '编辑活动'
                  }
                }
                return title
              }
            }}
          </h2>

          <Space v-show={!this.isPreview}>
            <Button
              onClick={() => {
                this.saveOrPublish(false)
              }}
              size="large"
              disabled={this.publishLoading}
              loading={this.saveLoading}
              style={{ width: '150px' }}
            >
              保存
            </Button>
            <Button
              onClick={() => this.saveOrPublish(true)}
              type="primary"
              size="large"
              disabled={this.saveLoading}
              loading={this.publishLoading}
              style={{ width: '150px' }}
            >
              发布
            </Button>
          </Space>
        </Row>

        <Row
          ref="containerRef"
          type="flex"
          style={{ marginTop: '10px' }}
          gutter={[10, 10]}
        >
          <Col span={24}>
            <Card>
              <h3>基本信息</h3>
              <Row>
                <Col span={10}>
                  <Form>
                    <FormItem label="活动标题" required>
                      <Input
                        disabled={this.isPreview}
                        placeholder="请输入活动标题"
                        v-model:value={this.actData.activityTitle}
                        style={{ width: '400px' }}
                      ></Input>
                    </FormItem>
                    <FormItem label="活动时间" required>
                      <RangePicker
                        disabled={this.isPreview}
                        v-model:value={this.actData.timeRangeTemp}
                        showTime={{
                          hideDisabledOptions: true,
                          defaultValue: [
                            moment('00:00:00', 'HH:mm:ss'),
                            moment('23:59:59', 'HH:mm:ss')
                          ]
                        }}
                        format={'YYYY-MM-DD HH:mm:ss'}
                        separator={'至'}
                        style={{ width: '400px' }}
                      />
                    </FormItem>
                    <FormItem label="答对奖励" required>
                      <Space>
                        <InputNumber
                          disabled={this.isPreview}
                          v-model:value={this.actData.questionPoint}
                          style={{ width: '100px' }}
                          min={0}
                          precision={0}
                          maxlength={4}
                        ></InputNumber>
                        积分/题
                      </Space>
                    </FormItem>
                    <FormItem label="选项乱序" required>
                      <RadioGroup
                        disabled={this.isPreview}
                        v-model:value={this.actData.isDisorder}
                      >
                        <Radio value={true}>是</Radio>
                        <Radio value={false}>否</Radio>
                      </RadioGroup>
                    </FormItem>
                  </Form>
                </Col>
                <Col span={3.5}>
                  <Form>
                    <FormItem label="背景图" required>
                      <UploadFile
                        disabled={this.isPreview}
                        v-model={[this.actData.backgroundImg, 'urls']}
                      >
                        上传图片
                      </UploadFile>
                      <p style={{ color: '#666', fontSize: '12px' }}>
                        建议尺寸 750*1624
                      </p>
                    </FormItem>
                  </Form>
                </Col>
                <Col span={3.5}>
                  <Form>
                    <FormItem label="规则图" required>
                      <UploadFile
                        disabled={this.isPreview}
                        v-model={[this.actData.activityRulesImg, 'urls']}
                      >
                        上传图片
                      </UploadFile>
                      <p style={{ color: '#666', fontSize: '12px' }}>
                        建议尺寸 654*高度不限
                      </p>
                    </FormItem>
                  </Form>
                </Col>
                <Col span={3.5}>
                  <Form>
                    <FormItem label="转发图" required>
                      <UploadFile
                        disabled={this.isPreview}
                        v-model={[this.actData.shareImg, 'urls']}
                      >
                        上传图片
                      </UploadFile>
                      <p style={{ color: '#666', fontSize: '12px' }}>
                        建议尺寸 500*400
                      </p>
                    </FormItem>
                  </Form>
                </Col>
              </Row>
            </Card>
          </Col>
          <Col span={5}>
            <Card>
              <h3>问题类型</h3>
              <Row
                wrap={true}
                type="flex"
                justify="space-between"
                gutter={[0, 10]}
                v-show={!this.isPreview}
              >
                <Button
                  onClick={() => {
                    this.addQuestion(0)
                  }}
                >
                  单选题
                </Button>
                <Button
                  onClick={() => {
                    this.addQuestion(1)
                  }}
                >
                  多选题
                </Button>
                <Button
                  onClick={() => {
                    this.addQuestion(2)
                  }}
                >
                  判断题
                </Button>
              </Row>
            </Card>
          </Col>
          <Col span={12}>
            <Card>
              <h3>问题列表</h3>
              <div
                style={{
                  paddingBottom: '400px',
                  overflowY: 'scroll',
                  maxHeight: '755px'
                }}
                ref="questionListRef"
              >
                <Space
                  direction="vertical"
                  style={{
                    width: '100%'
                  }}
                  size="large"
                >
                  {this.actData.questionList?.map((item, index) => {
                    let title
                    switch (item.questionType) {
                      //单选题
                      case 0:
                        title = '这是一道单选题'
                        break
                      //多选题
                      case 1:
                        title = '这是一道多选题'
                        break
                      //判断题
                      case 2:
                        title = '这是一道判断'
                        break
                    }
                    return (
                      <Row type="flex">
                        <Col
                          span={18}
                          style={{ cursor: 'pointer' }}
                          onClick={() => {
                            if (!this.isPreview) {
                              this.editQuesion(index, item)
                            }
                          }}
                        >
                          <h3
                            style={{
                              color: item.perfected ? '' : '#ff4d4f'
                            }}
                          >{`${index + 1}. ${item.question || title}`}</h3>

                          <Space
                            direction="vertical"
                            style={{ marginLeft: '20px' }}
                          >
                            {item.optionList.map((item, index) => {
                              return (
                                <div style={{ display: 'flex' }}>
                                  <TypographyText style={{ maxWidth: '400px' }}>
                                    {`${String.fromCharCode(
                                      'A'.charCodeAt(0) + index
                                    )}. ${item.optionDesc || '未设置'}`}
                                  </TypographyText>
                                  <TypographyText
                                    style={{
                                      width: '60px',
                                      marginLeft: '20px'
                                    }}
                                    v-show={item.isCorrect}
                                    type="success"
                                  >
                                    正确答案
                                  </TypographyText>
                                </div>
                              )
                            })}
                          </Space>
                        </Col>
                        <Col span={6}>
                          <Space size="small" v-show={!this.isPreview}>
                            <Button
                              type="link"
                              onClick={() => this.handleSort(index)}
                            >
                              排序
                            </Button>
                            <TypographyText
                              style={{ cursor: 'pointer' }}
                              type="danger"
                              onClick={() => {
                                this.actData.questionList.splice(index, 1)
                                this.questionItemCur = {} as QuesionItem
                              }}
                            >
                              删除
                            </TypographyText>
                          </Space>
                        </Col>
                      </Row>
                    )
                  })}
                </Space>
              </div>
            </Card>
          </Col>
          <Col span={7}>
            <Card>
              <h3>
                {`编辑${
                  this.questionItemCur?.optionList
                    ? `问题${this.questionItemCur.sort + 1}`
                    : ''
                }`}
              </h3>
              <Form
                v-show={this.questionItemCur?.optionList}
                labelCol={{ span: 5 }}
              >
                <FormItem label={`问题`} required>
                  {() => {
                    let placeholder
                    switch (this.questionItemCur.questionType) {
                      //单选题
                      case 0:
                        placeholder = '这是一道单选题'
                        break
                      //多选题
                      case 1:
                        placeholder = '这是一道多选题'
                        break
                      //判断题
                      case 2:
                        placeholder = '这是一道判断'
                        break
                    }
                    return (
                      <Textarea
                        placeholder={placeholder}
                        v-model:value={this.questionItemCur.question}
                        style={{ width: '300px' }}
                      ></Textarea>
                    )
                  }}
                </FormItem>

                {this.questionItemCur.optionList?.map((item, index) => {
                  return (
                    <FormItem
                      label={index === 0 ? '选项' : ' '}
                      colon={index === 0}
                      required={index === 0}
                    >
                      {this.questionItemCur.questionType == 1 ? (
                        <Checkbox
                          style={{ marginRight: '8px' }}
                          v-model:checked={item.isCorrect}
                          onClick={() => {
                            this.questionItemCur.optionList[index].isCorrect =
                              !this.questionItemCur.optionList[index].isCorrect
                          }}
                        ></Checkbox>
                      ) : (
                        <Radio
                          v-model:checked={item.isCorrect}
                          onClick={() => {
                            this.questionItemCur.optionList.forEach(item => {
                              item.isCorrect = false
                            })
                            this.questionItemCur.optionList[index].isCorrect =
                              true
                          }}
                        ></Radio>
                      )}
                      <Input
                        v-slots={{
                          prefix: () =>
                            `${String.fromCharCode('A'.charCodeAt(0) + index)}.`
                        }}
                        v-model:value={item.optionDesc}
                        placeholder={'请输入选项'}
                        style={{ width: '70%', marginRight: '8px' }}
                      ></Input>
                      <MinusCircleOutlined
                        v-show={
                          index > 0 && this.questionItemCur.questionType != 2
                        }
                        onClick={() => {
                          this.questionItemCur.optionList.splice(index, 1)
                        }}
                      />
                    </FormItem>
                  )
                })}

                <FormItem
                  v-show={this.questionItemCur.questionType != 2}
                  label=" "
                  colon={false}
                >
                  <Button
                    type="dashed"
                    style={{ width: '70%', marginLeft: '25px' }}
                    onClick={() => {
                      this.questionItemCur.optionList.push({
                        optionDesc: '',
                        isCorrect: false,
                        sort: this.questionItemCur.optionList.length
                      })
                    }}
                  >
                    <PlusOutlined />
                    增加选项
                  </Button>
                </FormItem>

                <FormItem label=" " colon={false}>
                  <Button
                    type="primary"
                    style={{
                      width: '70%',
                      marginTop: '50px',
                      marginLeft: '25px'
                    }}
                    onClick={this.handleEditSave}
                  >
                    保存
                  </Button>
                </FormItem>
              </Form>
            </Card>
          </Col>
        </Row>

        <Modal
          v-model:visible={this.showSortDialog}
          width={500}
          title={'排序'}
          destroyOnClose
          onOk={this.sortConfirm}
        >
          <Form labelCol={{ span: 5 }} style={{ marginTop: '15px' }}>
            <FormItem label={'排序'} required>
              <InputNumber
                style={{ width: '300px' }}
                v-model:value={this.sortCur}
                placeholder="请输入"
                precision={0}
                maxlength={3}
                min={1}
              />
            </FormItem>
          </Form>
        </Modal>
      </Spin>
    )
  }
})
